package com.example.demo;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName:VolatileDemo
 * @Description: 验证volatile可见性demo
 * @Author:Deamer
 * @Date:2021/11/14 20:36
 **/

// 设置这是主物理内存
class MyData {
        volatile int number = 0;
//    int number = 0;

    public void addToNum(int num) {
        this.number = 60;
    }

}

/**
 * 验证volatile的可见性
 */
public class VolatileDemo {
    public static void main(String args[]) {
        // 资源类
        MyData myData = new MyData();
        // 线程1：A线程实现了Runnable接口，lambda表达式
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t come in");
            // 线程睡眠3秒，假设在进行运算
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 修改值
            myData.addToNum(60);
            // 修改输出后的值
            System.out.println(Thread.currentThread().getName() + "\t update number value:" + myData.number);
        }, "A").start();
        // 线程2：主线程
        // main线程就一直在这循环，直到number不等于0
        while (myData.number == 0) {


        }
        System.out.println(Thread.currentThread().getName() + "\t mission is over");
    }
}
